package main

import (
	"bytes"
	"fmt"
	"math/rand"
	"runtime"
	"strconv"
	"time"
)

func main() {
	ch := make(chan int, 10)
	go prod(ch)
	go prod(ch)
	go prod(ch)
	go prod(ch)
	go prod(ch)
	go consumer(ch)
	go consumer(ch)
	go consumer(ch)

	time.Sleep(20 * time.Second)
}

func prod(ch chan<- int) {
	ticker := time.NewTicker(1 * time.Second)
	for range ticker.C {
		num := rand.Intn(10)
		ch <- num
		fmt.Printf("生产者%d生产了：%d\n", GetGID(), num)
	}
}
func consumer(ch <-chan int) {
	ticker := time.NewTicker(1 * time.Second)
	for range ticker.C {
		fmt.Printf("消费者%d消费了:%d\n", GetGID(), <-ch)
	}
}
func GetGID() uint64 {
	b := make([]byte, 64)
	b = b[:runtime.Stack(b, false)]
	b = bytes.TrimPrefix(b, []byte("goroutine "))
	b = b[:bytes.IndexByte(b, ' ')]
	n, _ := strconv.ParseUint(string(b), 10, 64)
	return n
}
